package org.bdware.doip.core.crypto;

import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.jwk.JWK;
import org.apache.log4j.Logger;
import org.bdware.doip.core.utils.GlobalConfigurations;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.text.ParseException;

public class GlobalCertifications {

    static Logger logger = Logger.getLogger(GlobalCertifications.class);

    /**
     * Global Instance
     */
    public static JWK jwKeyPair;
//    public static KeyPair rawKeyPair;
    public static KeyStore localKeyStore;

    public static boolean needAuthentication = false;
    public static boolean secureMode = false;

    /**
     *
     * @return localKeyPair for signature
     */
    public static JWK getGlobalJWK() {
        if (jwKeyPair == null) {
            logger.error("keyPair not initialized yet! ");
        }
        return jwKeyPair;
    }

//    public static KeyPair getGlobalRawKeyPair(){
//        if (rawKeyPair == null) {
//            logger.error("keyPair not initialized yet! ");
//        }
//        return rawKeyPair;
//    }

    public static KeyStore getGlobalKeyStore() {
        if (localKeyStore == null) {
            logger.error("keyPair not initialized yet! ");
        }
        return localKeyStore;
    }

    public static void loadKeysFromJKS(String certFilePath, String password) throws Exception {
        localKeyStore = KeyStore.getInstance("JKS");
        localKeyStore.load(new FileInputStream(certFilePath), password.toCharArray());
        jwKeyPair = JWK.load(localKeyStore,"myKey",password.toCharArray());
        logger.info(jwKeyPair.toString());
    }

    public static void loadKeysFromJWK(String jwkFilePath) throws IOException, ParseException {
        FileInputStream fi = new FileInputStream(jwkFilePath);
        byte[] jwkB = new byte[fi.available()];
        fi.read(jwkB);
        String jwkS = new String(jwkB);
        logger.info(jwkS);
        jwKeyPair = JWK.parse(jwkS);
        GlobalConfigurations.userID = jwKeyPair.getKeyID();
    }

}
